﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Newtonsoft.Json;
using Supore.APP.UI;
using Supore.APP.UI.Controls.Notify;
using SuporeSliplampApp.Control;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.Service;
using SuporeSliplampApp.Util;
using SuporeSliplampApp.ViewModels;
using static SuporeSliplampApp.Views.IDSettingView;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// NewPatientView.xaml 的交互逻辑
    /// </summary>
    public partial class NewPatientView : Window
    {
        NewPatientViewModel viewModel;
        AddPatientService service;

        private string patid;
        private int patLength;
        private bool isIDSwitchOn;

        public NewPatientView()
        {
            InitializeComponent();
            viewModel = new NewPatientViewModel();
            service = new AddPatientService();
            DataContext = viewModel;
            init();
        }


        private void init()
        {
            LoadIDSettings();
            int currentnum = 1;
            if (isIDSwitchOn)
            {
                string id ;

                while(true)
                {
                    int zeroL = patLength - currentnum.ToString().Length;
                    if (zeroL < 0)
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            MessageBox.Show("编号超出预设长度上限");
                        }
                        else
                        {
                            MessageBox.Show("The number exceeds the predefined length limit");
                        }

                        //int breakindex = 0;
                        break;
                    }
                    id = patid + new string('0', zeroL) + currentnum;

                    if(!service.PatidExist(id))
                    {
                        p_ID.Text = id;
                        p_ID.IsEnabled = false;
                        break;
                    }

                    currentnum++;   


                }
                
            }
        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void SubmitBtn_Click(object sender, RoutedEventArgs e)
        {

            if (string.IsNullOrEmpty(p_name.Text))
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("姓名不能为空!");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Name is required!");
                }
                return;
            }
            if (string.IsNullOrEmpty(p_ID.Text))
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("病人ID不能为空！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "ID is required!");
                }
                return;
            }
            if (string.IsNullOrEmpty(p_birth.Text))
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("生日不能为空！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Birthday is required!");
                }
                return;
            }
            if (p_sex.SelectedIndex == -1)
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("性别不能为空！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Gender is required!");
                }
                return;
            }
            if (p_ID.Text.Length > 25)
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("病人ID过长！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "ID is too long!");
                }
                return;
            }
            PatientModel model = new PatientModel();
            model.Name = p_name.Text;
            model.P_ID = p_ID.Text;
            ComboBoxItem cbi = (ComboBoxItem)p_sex.SelectedItem;
            model.SEX = cbi.Content.ToString();
            model.Birth = p_birth.SelectedDate.Value;
            model.Adreess = p_adress.Text;
            model.PhoneNum = p_phone.Text;
            model.Email = p_email.Text;
            model.Creator = App.Current.Properties["UserName"].ToString();
            if (!service.AddPatient(model))
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("保存失败！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Save Failed!");
                }
                return;
            }
            else
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowSuccess("保存成功！");
                }
                else
                {
                    LayUINotify.ShowSuccess("Tip", "Save Successful!");
                }

            }
            MainViewModel.GetInstance().patientModel.Name = model.Name;
            MainViewModel.GetInstance().patientModel.P_ID = model.P_ID;
            MainViewModel.GetInstance().patientModel.SEX = model.SEX;
            MainViewModel.GetInstance().patientModel.Str_Birth = model.Birth.ToShortDateString();
            MainViewModel.GetInstance().patientModel.Birth = model.Birth;
            MainViewModel.GetInstance().patientModel.Adreess = model.Adreess;
            MainViewModel.GetInstance().patientModel.PhoneNum = model.PhoneNum;
            MainViewModel.GetInstance().patientModel.Email = model.Email;
            MainViewModel.GetInstance().patientModel.Creator = model.Creator;

            if (Common.isAddToNow)
            {
                ResultModel result = new ResultModel();
                ScrollControl sc = new ScrollControl();
                ListControlModel photo = new ListControlModel();
                VideoModel video = new VideoModel();
                if (Common.scrolllist.Count > 0)
                {
                    for (int i = 0; i < Common.scrolllist.Count; i++)
                    {
                        sc = (ScrollControl)Common.scrolllist[i];
                        photo = sc.DataContext as ListControlModel;
                        video = sc.DataContext as VideoModel;
                        try
                        {
                            if (video == null)
                            {
                                result.Id = model.P_ID;
                                result.Description = null;
                                result.Date = DateTime.Now;
                                result.Name = photo.ImageName;
                                result.Path = photo.ImgPath;
                                service.SaveResults(result);
                            }
                            else
                            {
                                result.Id = model.P_ID;
                                result.Description = null;
                                result.Date = DateTime.Now;
                                result.Path = video.VideoPath;
                                result.Name = video.Name;
                                service.SaveResults(result);
                            }
                        }
                        catch { }
                    }
                }
                HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.CameraView");
            }

            this.Close();
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
           this.Close();
        }

        private void LoadIDSettings()
        {
            if(File.Exists("idsettings.json"))
            {
                string json = File.ReadAllText("idsettings.json");
                var idsettings = JsonConvert.DeserializeObject<IDSettings>(json);

                patid = idsettings.Patid;
                patLength =idsettings.PatidLength;
                isIDSwitchOn = idsettings.IsIDSwitchOn;

            }
        }



    }
}
